package com.cskaoyan.service.user;

import com.cskaoyan.bean.goods.Goods;
import com.cskaoyan.bean.market.OrderExample;
import com.cskaoyan.bean.market.Region;
import com.cskaoyan.bean.user.UserExample;
import com.cskaoyan.bean.user.*;
import com.cskaoyan.bo.user.WxAddressBo;
import com.cskaoyan.bo.user.WxCollectBo;
import com.cskaoyan.mapper.*;
import com.cskaoyan.utils.Converter;
import com.cskaoyan.utils.DataUtils;
import com.cskaoyan.utils.PojoUtils;
import com.cskaoyan.vo.user.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    FeedbackMapper feedbackMapper;

    @Autowired
    SearchHistoryMapper searchHistoryMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    RegionMapper regionMapper;

    @Autowired
    FootprintMapper footprintMapper;

    @Autowired
    AddressMapper addressMapper;

    @Autowired
    CollectMapper collectMapper;
    @Autowired
    GoodsMapper goodsMapper;

    @Override//会员管理
    public UserListVo query(String username, String mobile, Integer page, Integer limit, String sort, String order) {
        // 分页
        PageHelper.startPage(page, limit);  //mybatis在构建sql语句的时候，会构造limit和offset

        UserExample userExample = new UserExample();
        userExample.setOrderByClause(sort + " " + order);
        UserExample.Criteria criteria = userExample.createCriteria();
        if (!ObjectUtils.isEmpty(username)) {
            criteria.andUsernameLike("%" + username + "%");
        }
        if (!ObjectUtils.isEmpty(mobile)) {
            criteria.andMobileEqualTo(mobile);
        }
        // limit为多少，查出来的数据就有多少条
        List<User> users = userMapper.selectByExample(userExample);

        // total != users.size()
        // total是满足当前条件的所有数据量，不是当前的limit

        // 可以通过PageInfo获得分页信息
        PageInfo<User> userPageInfo = new PageInfo<>(users);
        // 获得总的数据量：通过select (*) 限制条件是byExample
        long total = userPageInfo.getTotal();

        UserListVo userListVo = new UserListVo();
        userListVo.setItems(users);
        userListVo.setTotal(total);
        return userListVo;
    }

    @Override//会员收藏
    public DataVo collectQuery(Integer userId, Integer valueId, Integer page, Integer limit, String sort, String order) {
        PageHelper.startPage(page, limit);
        CollectExample collectExample = new CollectExample();
        CollectExample.Criteria criteria = collectExample.createCriteria();
        if (!ObjectUtils.isEmpty(userId)) {
            criteria.andUserIdEqualTo(userId);
        }
        if (!ObjectUtils.isEmpty(valueId)) {
            criteria.andValueIdEqualTo(valueId);
        }
        if (!ObjectUtils.isEmpty(sort) && !ObjectUtils.isEmpty(order)) {
            collectExample.setOrderByClause(sort + " " + order);
        }
        List<Collect> collects = collectMapper.selectByExample(collectExample);
        PageInfo<Collect> collectPageInfo = new PageInfo<>(collects);
        long total = collectPageInfo.getTotal();
        DataVo<Collect> dataVo = new DataVo<>();
        dataVo.setItems(collects);
        dataVo.setTotal(total);
        //Map<String ,Object> res = new HashMap<>();
        //res.put("items",)
        return dataVo;
    }

    @Override//会员足迹
    public DataVo footprintQuery(Integer goodsId, Integer userId, Integer page, Integer limit, String sort, String order) {
        PageHelper.startPage(page, limit);
        FootprintExample footprintExample = new FootprintExample();
        FootprintExample.Criteria criteria = footprintExample.createCriteria();
        if (!ObjectUtils.isEmpty(goodsId)) {
            criteria.andGoodsIdEqualTo(goodsId);
        }
        if (!ObjectUtils.isEmpty(userId)) {
            criteria.andUserIdEqualTo(userId);
        }
        List<Footprint> footprints = footprintMapper.selectByExample(footprintExample);
        PageInfo<Footprint> pageInfo = new PageInfo<>(footprints);
        long total = pageInfo.getTotal();
        DataVo<Footprint> dataVo = new DataVo<>();
        dataVo.setTotal(total);
        dataVo.setItems(footprints);

        return dataVo;
    }

    @Override//搜索历史
    public DataVo historyQuery(Integer userId, String keyword, Integer page, Integer limit, String sort, String order) {
        PageHelper.startPage(page, limit);
        SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
        SearchHistoryExample.Criteria criteria = searchHistoryExample.createCriteria();
        if (!ObjectUtils.isEmpty(userId)) {
            criteria.andUserIdEqualTo(userId);
        }
        if (!ObjectUtils.isEmpty(keyword)) {
            criteria.andKeywordLike("%" + keyword + "%");
        }
        List<SearchHistory> searchHistories = searchHistoryMapper.selectByExample(searchHistoryExample);
        long total = new PageInfo<>(searchHistories).getTotal();
        DataVo<SearchHistory> dataVo = new DataVo<>();
        dataVo.setItems(searchHistories);
        dataVo.setTotal(total);
        return dataVo;
//        return new DataVo();
    }

    @Override//意见反馈
    public DataVo feedbackQuery(String username, Integer id, Integer page, Integer limit, String sort, String order) {
        PageHelper.startPage(page, limit);
        FeedbackExample feedbackExample = new FeedbackExample();
        FeedbackExample.Criteria criteria = feedbackExample.createCriteria();
        if (!ObjectUtils.isEmpty(username)) {
            criteria.andUsernameLike("%" + username + "%");
        }
        if (!ObjectUtils.isEmpty(id)) {
            criteria.andIdEqualTo(id);
        }
        List<Feedback> feedbacks = feedbackMapper.selectByExample(feedbackExample);
        long total = new PageInfo<>(feedbacks).getTotal();
        DataVo<Feedback> dataVo = new DataVo<>();
        dataVo.setTotal(total);
        dataVo.setItems(feedbacks);
        return dataVo;
    }

    @Override
    public Map<String, String> wxCollectAD(WxCollectBo wxCollectBo) {

        Subject subject = SecurityUtils.getSubject();
        WxUserLoginData loginData = (WxUserLoginData) subject.getPrincipal();

        Byte type = wxCollectBo.getType();
        Integer valueId = wxCollectBo.getValueId();
        CollectExample collectExample = new CollectExample();
        CollectExample.Criteria criteria = collectExample.createCriteria();
        criteria.andTypeEqualTo(type).andValueIdEqualTo(valueId);
        List<Collect> list = collectMapper.selectByExample(collectExample);
        HashMap<String, String> map = new HashMap<>();
        if (list.isEmpty()) {
            //db中未查询到数据
            //Integer id;
            //Integer userId;
            //Integer valueId;
            //Byte type;
            //Date addTime;
            //Date updateTime;
            //Boolean deleted;

            Integer userId = loginData.getId();
            Collect collect =
                    new Collect(null, userId, valueId, type, DataUtils.getCurrentTime(), DataUtils.getCurrentTime(), false);
            //缺获取当前用户Id
//            collect.setUserId(1205);
            collect.setUserId(loginData.getId());

            collectMapper.insertSelective(collect);
            map.put("type", "add");
        } else {
            //存在此条收藏记录
            Boolean deleted = list.get(0).getDeleted();
            Collect collect = new Collect();
            collect.setDeleted(!deleted);
            collectMapper.updateByExampleSelective(collect, collectExample);
            if (deleted == true) {
                map.put("type", "add");
            } else {
                map.put("type", "delete");
            }
        }
        return map;
    }

    @Override
    public Map<String, Object> wxCollectQuery(Byte type, Integer page, Integer size) {
        Subject subject = SecurityUtils.getSubject();
        WxUserLoginData loginData = (WxUserLoginData) subject.getPrincipal();
        Integer userId = loginData.getId();

        PageHelper.startPage(page, 10);
        CollectExample collectExample = new CollectExample();
        collectExample.createCriteria()
                .andTypeEqualTo(type)
                .andUserIdEqualTo(userId);
        List<Collect> collects = collectMapper.selectByExample(collectExample);
        List<WxCollectListVo> list = new ArrayList<>();

        for(Collect collect:collects){
            Goods goods = goodsMapper.selectByPrimaryKey(collect.getValueId());
            WxCollectListVo wxCollectListVo = new WxCollectListVo();
            WxCollectListVo vo = PojoUtils.converter().converter(goods, wxCollectListVo);
            vo.setType(collect.getType());
            vo.setValueId(collect.getValueId());
            vo.setRetailPrice(goods.getRetailPrice());
            list.add(vo);
        }
        PageInfo<WxCollectListVo> pageInfo = new PageInfo<>(list);
        long total = pageInfo.getTotal();
        long totalPages = (total/size) + 1;
        HashMap<String, Object> map = new HashMap<>();
        map.put("totalPages", totalPages);
        map.put("collectList", list);

        return map;
    }

    @Override
    public List<WxAddressListVo> wxAddressQuery(Integer userId) {
        AddressExample addressExample = new AddressExample();
        addressExample.createCriteria().andUserIdEqualTo(userId);
        List<Address> addresses = addressMapper.selectByExample(addressExample);
        ArrayList<WxAddressListVo> list = new ArrayList<>();
        for (Address address : addresses) {
            WxAddressListVo vo = new WxAddressListVo();
            vo.setId(address.getId());
            vo.setMobile(address.getMobile());
            vo.setIsDefault(address.getIsDefault());
            vo.setName(address.getName());

            //得到id👉主键查询address👉得到省市区名
            //p+c+a+get
            vo.setDetailedAddress(
                    regionMapper.selectByPrimaryKey(address.getProvinceId()).getName()//province
                            + regionMapper.selectByPrimaryKey(address.getCityId()).getName()  //city
                            + regionMapper.selectByPrimaryKey(address.getAreaId()).getName()  //area
                            + " " + address.getAddress());

            list.add(vo);
        }
        return list;
    }

    @Override
    public Map<String, Object> wxDetailQuery(Integer id) {
        HashMap<String, Object> map = new HashMap<>();
        Address address = addressMapper.selectByPrimaryKey(id);
//        "isDefault": false,
//        "areaId": 1289,
//        "address": "碧桂园",
//        "cityName": "合肥市",
//        "areaName": "瑶海区",
//        "name": "张松",
//        "mobile": "18566549962",
//        "id": 4,
//        "cityId": 130,
//        "provinceName": "安徽省",
//        "provinceId": 12
        map.put("isDefault", address.getIsDefault());
        map.put("areaId", address.getAreaId());
        map.put("address", address.getAddress());
        map.put("cityName", regionMapper.selectByPrimaryKey(address.getCityId()).getName());
        map.put("areaName", regionMapper.selectByPrimaryKey(address.getAreaId()).getName());
        map.put("name", address.getName());
        map.put("mobile", address.getMobile());
        map.put("id", id);
        map.put("cityId", address.getCityId());
        map.put("provinceName", regionMapper.selectByPrimaryKey(address.getProvinceId()).getName());
        map.put("provinceId", address.getProvinceId());
        return map;
    }

    @Override
    public Integer wxAddressSave(WxAddressBo wxAddressBo) {//id为修改的地址  userId为当前用户id

        Subject subject = SecurityUtils.getSubject();
        WxUserLoginData loginData = (WxUserLoginData) subject.getPrincipal();
        Integer id = wxAddressBo.getId();


        if(id == 0){
            //id if = 0 则是新建  否则是修改
            Integer userId = loginData.getId();                                                         //第一处
            Address addressAdd = new Address();
            PojoUtils.converter().converter(wxAddressBo,addressAdd);
            addressAdd.setUserId(userId);
            addressAdd.setAddTime(DataUtils.getCurrentTime());
            addressAdd.setUpdateTime(DataUtils.getCurrentTime());
            addressAdd.setDeleted(false);

            //设为默认地址
            if (wxAddressBo.getIsDefault() == true) {//若是改为默认值 先清除当前用户所有true再将其置为true
                AddressExample addressesExampleIsDefault = new AddressExample();
                addressesExampleIsDefault.createCriteria()
                        .andUserIdEqualTo(userId)//当前用户的其他true
                        .andIsDefaultEqualTo(true);//Example筛选条件为IsDefault为true
                Address addressDefault = new Address();
                addressDefault.setIsDefault(false);
                addressMapper.updateByExampleSelective(addressDefault, addressesExampleIsDefault);//将为true的置为false
            }

            addressMapper.insert(addressAdd);
            AddressExample addressExample = new AddressExample();
            addressExample.createCriteria()
                    .andUserIdEqualTo(userId).andIsDefaultEqualTo(addressAdd.getIsDefault()).andAreaIdEqualTo(addressAdd.getAreaId())
                    .andAddTimeEqualTo(addressAdd.getAddTime()).andUpdateTimeEqualTo(addressAdd.getUpdateTime())
                    .andCityIdEqualTo(addressAdd.getCityId()).andProvinceIdEqualTo(addressAdd.getProvinceId());
            List<Address> addresses = addressMapper.selectByExample(addressExample);
            Integer newId = addresses.get(0).getId();

            return newId;//缺少共同的设为默认地址
        }
        AddressExample addressExample = new AddressExample();
        // TODO：虚假的UserId
        // Integer userId = addressMapper.selectByPrimaryKey(id).getUserId();               //第二处
        Integer userId = addressMapper.selectByPrimaryKey(id).getUserId();               //第二处


        addressExample.createCriteria().andUserIdEqualTo(userId);

        //设为默认地址
        if (wxAddressBo.getIsDefault() == true) {//若是改为默认值 先清除当前用户所有true再将其置为true
            AddressExample addressesExampleIsDefault = new AddressExample();
            addressesExampleIsDefault.createCriteria()
                    .andUserIdEqualTo(userId)//当前用户的其他true
                    .andIsDefaultEqualTo(true);//Example筛选条件为IsDefault为true
            Address addressDefault = new Address();
            addressDefault.setIsDefault(false);
            addressMapper.updateByExampleSelective(addressDefault, addressesExampleIsDefault);//将为true的置为false
        }

        Address address = new Address();
        PojoUtils.converter().converter(wxAddressBo, address);
        address.setUpdateTime(DataUtils.getCurrentTime());//除了传入的数据同时更新属性中的更新时间

        addressMapper.updateByPrimaryKeySelective(address);//传入的主键id修改值 null的地方不会改变
        return id;
    }

    @Override
    public void wxAddressDelete(Map<String,Integer> map) {
        Integer id = map.get("id");
        Address address = new Address();
        address.setId(id);
        address.setDeleted(true);
        address.setUpdateTime(DataUtils.getCurrentTime());
        addressMapper.updateByPrimaryKeySelective(address);
    }

    @Override
    public Map<String, Object> wxUnNumQuery(Integer userId) {
        HashMap<String, Object> order = new HashMap<>();
//        "order": {
//                "unrecv": 0,
//                "uncomment": 0,
//                "unpaid": 2,
//                "unship": 1
        OrderExample orderExampleUnpaid = new OrderExample();
        orderExampleUnpaid.createCriteria().andUserIdEqualTo(userId).andOrderStatusEqualTo((short) 101);
        long unpaid = orderMapper.countByExample(orderExampleUnpaid);
        order.put("unpaid",unpaid);

        OrderExample orderExampleUncomment = new OrderExample();
        orderExampleUncomment.createCriteria().andUserIdEqualTo(userId).andOrderStatusEqualTo((short)401);
        long uncomment = orderMapper.countByExample(orderExampleUncomment);
        order.put("uncomment",uncomment);

        OrderExample orderExampleUnrecv = new OrderExample();
        orderExampleUnrecv.createCriteria().andUserIdEqualTo(userId).andOrderStatusEqualTo((short)301);
        long unrecv = orderMapper.countByExample(orderExampleUnrecv);
        order.put("unrecv",unrecv);

        OrderExample orderExampleUnship = new OrderExample();
        orderExampleUnship.createCriteria().andUserIdEqualTo(userId).andOrderStatusEqualTo((short)201);
        long unship = orderMapper.countByExample(orderExampleUnship);
        order.put("unship",unship);

        return order;
    }

    @Override//收货地址
    public DataVo addressQuery(String name, Integer userId, Integer page, Integer limit, String sort, String order) {
        PageHelper.startPage(page, limit);
        AddressExample addressExample = new AddressExample();
        AddressExample.Criteria criteria = addressExample.createCriteria();
        if (!ObjectUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (!ObjectUtils.isEmpty(userId)) {
            criteria.andUserIdEqualTo(userId);
        }
        addressExample.setOrderByClause(sort + " " + order);
        List<Address> addresses = addressMapper.selectByExample(addressExample);
        long total = new PageInfo<>(addresses).getTotal();
        ArrayList<AddressVo> addressVos = new ArrayList<>();
        Converter converter = PojoUtils.converter();
        converter.listConverter(addresses, addressVos, AddressVo.class);
        for (AddressVo addressVo : addressVos) {
            int areaId = addressVo.getAreaId();
            Region regionArea = regionMapper.selectByPrimaryKey(areaId);
            addressVo.setArea(regionArea.getName());
            int cityId = addressVo.getCityId();
            Region regionCity = regionMapper.selectByPrimaryKey(cityId);
            addressVo.setCity(regionCity.getName());
            int provinceId = addressVo.getProvinceId();
            Region regionProvince = regionMapper.selectByPrimaryKey(provinceId);
            addressVo.setProvince(regionProvince.getName());
        }
        DataVo<AddressVo> dataVo = new DataVo<>();
        dataVo.setItems(addressVos);
        dataVo.setTotal(total);
/*
        List<AddressVo> addressVoList = userMapper.selectAddress(page,limit,sort,order);
        DataVo dataVo = new DataVo();
        dataVo.setItems(addressVoList);
        int size = addressVoList.size();
        dataVo.setTotal(size);*/
        return dataVo;
    }


}
